<template>
  <div
    :class="className"
    :style="{ height: height, width: width }"
    ref="chartContainer"
  />
</template>

<script setup>
import * as echarts from "echarts";

const animationDuration = 3000;

// 接收 props
const props = defineProps({
  className: {
    type: String,
    default: "chart",
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "300px",
  },
  title: {
    type: String,
    default: "",
  },
  data: {
    type: Object,
    default: {},
  },
  tooltip: {
    type: String,
    default: "",
  },
});

const chartContainer = ref(null);
let chartInstance = null;

const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value, "macarons");

    chartInstance.setOption({
      title: {
        text: props.title,
        left: "center",
      },
      tooltip: {
        trigger: "item",
        axisPointer: {
          type: "shadow",
        },
      },
      legend: {},
      toolbox: {
        show: true,
        feature: {
          dataZoom: {
            yAxisIndex: "none",
          },
          dataView: { readOnly: false },
          magicType: { type: ["line", "bar"] },
          restore: {},
          saveAsImage: {},
        },
      },
      grid: {
        top: 35,
        left: "2%",
        right: "2%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: [
        {
          type: "category",
          data: Object.keys(props.data),
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: [
        {
          type: "value",
          axisTick: {
            show: false,
          },
        },
      ],
      series: [
        {
          name: props.tooltip,
          type: "bar",
          stack: "vistors",
          barWidth: "60%",
          data: Object.values(props.data),
          animationDuration,
        },
      ],
    });
  }
};

/** 监听 props.data 变化并初始化 */
watch(
  () => props.data,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      initChart();
    }
  },
  { deep: true }
);

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});
</script>
